package btanalyzer.db.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

public abstract class GenericDaoAbstract<T, ID extends Serializable> implements GenericDao<T, ID> {

	protected Class<?> entityClass;

	@PersistenceContext
	protected EntityManager entityManager;
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * Default constructor
	 */
	public GenericDaoAbstract() {
		ParameterizedType genericSuperclass = (ParameterizedType) 
				getClass().getGenericSuperclass();
		this.entityClass = (Class<?>) genericSuperclass.getActualTypeArguments()[1];
	}
	
	/**
	 * @see btanalyzer.db.dao.GenericDao#delete(java.lang.Object)
	 */
	@Override
	@Transactional
	public void delete(T entity) {
		getEntityManager().remove(entity);
	}

	/**
	 * @see btanalyzer.db.dao.GenericDao#save(java.lang.Object)
	 */
	@Override
	@Transactional
	public T save(T entity) {
		final T savedEntity = getEntityManager().merge(entity);
		return savedEntity;
	}
	
	@Override
	public void flush() {
		getEntityManager().flush();
	}
}
